package com.ls.blog.controller;


import com.google.code.kaptcha.Producer;
import com.ls.blog.VO.Result;
import com.ls.blog.consts.Const;
import com.ls.blog.utils.R;
import com.ls.blog.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @program: blog
 * @author: lishun
 * @create: 2021-09-19 13:43
 **/
@Slf4j
@Api(value = "认证模块")
@RestController
public class AuthController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private Producer producer;
    /**
     * 图片验证码
     */
    @ApiOperation(value = "验证码生成")
    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

//        // 方便测试
        String code = "444";
        String key = "aaa";
//        String code = producer.createText();
//        String key = UUID.randomUUID().toString();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());
        // 存储到redis中
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);
        Map<String,String> map = new HashMap<>();
        map.put("token",key);
        map.put("base64Img",base64Img);
        return R.ok(map);
    }
}
